﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NBusiness.CodeDom.Compiler;
using NBusiness.CodeDom;
using System.CodeDom.Compiler;
using System.CodeDom;
using System.IO;

namespace NBusiness.Templates
{
    public abstract class CodeDomTemplateBase : TemplateBase
    {
        protected override string Compile(Entity entity, EntityCompileParameters parameters)
        {
            CodeTemplateParameters p1 = parameters as CodeTemplateParameters;
            if (p1 == null || p1.Provider == null)
                throw new ArgumentException("parameters");

            CodeDomProvider provider = p1.Provider;

            CodeCompileUnit unit = new CodeCompileUnit();
            Compile(entity, unit);

            MemoryStream stream = new MemoryStream();
            TextWriter writer = new StreamWriter(stream);
            provider.GenerateCodeFromCompileUnit(unit, writer, null);
            writer.Flush();
            string text = writer.Encoding.GetString(stream.ToArray());

            return text;
        }

        protected abstract void Compile(Entity entity, CodeCompileUnit root);
    }
}
